package com.heiyanquan.security.controller;

import com.heiyanquan.security.dto.UploadFileInfo;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author dingaolin
 * @Date: 2017/12/7 0007.
 */
@RestController
@RequestMapping("/file")
public class FileController {

    private final String folder = "D:\\Work\\authority\\heiyanquan-security\\heiyanquan-security-web\\src\\main\\java\\com\\heiyanquan\\security\\controller";

    @PostMapping
    public UploadFileInfo upload(MultipartFile inputFile) throws Exception {
        System.out.println(ReflectionToStringBuilder.reflectionToString(inputFile, ToStringStyle.MULTI_LINE_STYLE));

        File localFile = new File(folder, System.currentTimeMillis() + ".txt");
        inputFile.transferTo(localFile);

        return new UploadFileInfo(localFile.getAbsolutePath());
    }

    @GetMapping("/{id}")
    public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws Exception {
        try (InputStream inputStream = new FileInputStream(new File(folder, id + ".txt"));
             OutputStream outputStream = response.getOutputStream();
        ) {
            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename=test.txt");

            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
        }
    }
}
